package com.plum.admin.modules.common;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.plum.admin.common.exception.BaseException;
import com.plum.admin.common.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/9/3 14:02
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
    @Value("${web.uploadPath}")
    private String uploadPath;

    @PostMapping("uploadImg")
    @ApiOperation("文件上传")
    public R<Object> uploadFile(@RequestParam(name = "file") MultipartFile file){
        DateTime date = DateUtil.date();
        String format=date.year() + "/" + date.month()+1 + "/" + date.dayOfMonth();
        String path = uploadPath+format;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String name = FileUtil.extName(file.getOriginalFilename());
        String fileName= IdUtil.simpleUUID()+"."+ name;
        File f = new File(path + "/"+fileName);
        if (f.exists()) {
            throw new BaseException("文件名已存在");
        }
        try {
            file.transferTo(f);
        } catch (IOException e) {
            log.error(e.toString());
            throw new BaseException("上传文件出错");
        }
        return R.ok(format+"/"+fileName);
    }
}
